import { getToken, setToken, removeToken, getRouter, setRouter, removeRouter, setUserInfo, getUserInfo, removeUserInfo } from '@/utils/auth'
import { setDictObj, getDictObj } from '@/utils/dict'
import { api } from '@/api/api'
import Utils from '@/utils/AES.js'
import Vue from 'vue'
import { message } from 'util/message/message'
import moment from 'moment'

const user = {
  state: {
    token: getToken(),
    authRouters: JSON.parse(getRouter()), // 授权路由
    dictObj: JSON.parse(getDictObj()), // 字段缓存数据
    userStatus: '404', // 页面状态
    accountInfo: getUserInfo() ? JSON.parse(getUserInfo()) : null, // 用户信息
    avatar: '',
    badgeValue: 0, // 待办事项总数
    ossObj: localStorage.getItem('ossObj') ? JSON.parse(localStorage.getItem('ossObj')) : null, // oss对象
    menuIdex: localStorage.getItem('menuIdex') ? JSON.parse(localStorage.getItem('menuIdex')) : 0 // 首页菜单下标
  },
  mutations: {
    SET_TOKEN: (state, stoken) => {
      state.token = stoken
      setToken(stoken)
    },
    SET_AUTH_ROUTERS: (state, authRouters) => {
      state.authRouters = authRouters
      setRouter(JSON.stringify(authRouters))
    },
    SET_DICT_OBJ: (state, dictObj) => {
      state.dictObj = dictObj
      setDictObj(JSON.stringify(dictObj))
    },
    SET_USER_STATUS: (state, userStatus) => {
      state.userStatus = userStatus
    },
    SET_ACCOUNT_INFO: (state, accountInfo) => {
      state.accountInfo = accountInfo
      setUserInfo(JSON.stringify(accountInfo))
    },
    SET_BADGE_VALUE: (state, badgeValue) => {
      state.badgeValue = badgeValue
    },
    SET_OSS_OBJ: (state, ossObj) => {
      state.ossObj = ossObj
      localStorage.setItem('ossObj', JSON.stringify(ossObj))
    },
    SET_MENU_INDEX: (state, menuIdex) => {
      state.menuIdex = menuIdex
      localStorage.setItem('menuIdex', JSON.stringify(menuIdex))
    }
  },
  actions: {
    // 获取待办事项总数
    GetOssObj ({ commit }) {
      return new Promise((resolve, reject) => {
        Vue.prototype.$$get(api.oss.getToken()).then((response) => {
          if (response.success) {
            const data = response.content
            data.expiration = moment(data.expiration).format('YYYY-MM-DD HH:mm:ss')
            commit('SET_OSS_OBJ', data)
            resolve(data)
          } else {
            Vue.prototype.$message({
              type: 'warning',
              message: response.message
            })
          }
        }).catch((error) => {
          reject(error)
        })
      })
    },
    // 获取待办事项总数
    GetBadgeValue ({ commit }) {
      return new Promise((resolve, reject) => {
        Vue.prototype.$$get(api.instance.getApproveCount()).then((response) => {
          if (response.success) {
            const data = response.content
            let total = data.business +
              data.cashOut +
              data.contract +
              data.project +
              data.purchase +
              data.repayment +
              data.subject +
              data.task
            if (total > 99) {
              total = '99+'
            }
            commit('SET_BADGE_VALUE', total)
            resolve(total)
          } else {
            Vue.prototype.$message({
              type: 'warning',
              message: response.message
            })
          }
        }).catch((error) => {
          reject(error)
        })
      })
    },
    // 登录
    Login ({ commit }, userInfo) {
      let params = {
        phone: userInfo.account.trim(),
        password: Utils.encrypt(userInfo.password)
      }
      return new Promise((resolve, reject) => {
        Vue.prototype.$$post(api.login(), params).then((response) => {
          if (response.success) {
            const data = response.content
            commit('SET_TOKEN', data.Authorization)
            commit('SET_ACCOUNT_INFO', data.accountInfo)
            resolve(response)
          } else {
            Vue.prototype.$message({
              type: 'warning',
              message: response.message
            })
          }
        }).catch((error) => {
          reject(error)
        })
      })
    },
    // 修改密码
    changePwd ({ commit }, changeForm) {
      let params = {
        accountId: changeForm.accountId,
        oldPassword: Utils.encrypt(changeForm.oldPassword),
        newPassword: Utils.encrypt(changeForm.newPassword),
        confirmPassword: Utils.encrypt(changeForm.confirmPassword)
      }
      return new Promise((resolve, reject) => {
        Vue.prototype.$$post(api.my.updatePassword(), params).then((response) => {
          if (response.success) {
            commit('SET_TOKEN', '')
            commit('SET_AUTH_ROUTERS', [])
            commit('SET_DICT_OBJ', [])
            commit('SET_ACCOUNT_INFO', null)
            // 清除TOKEN
            removeToken()
            // 清除路由
            removeRouter()
            // 清楚用户信息
            removeUserInfo()
            localStorage.clear()
            resolve()
            // resolve(response)
          } else {
            Vue.prototype.$message({
              type: 'warning',
              message: response.message
            })
          }
        }).catch((error) => {
          reject(error)
        })
      })
    },
    // 获取路由菜单
    GetRouters ({ commit }) {
      return new Promise((resolve, reject) => {
        // 获取权限菜单
        Vue.prototype.$$get(api.permission.getAuth()).then(res => {
          if (res.success) {
            // 登录成功获取路由菜单后再提示成功登录
            message.success('成功登陆')
            let menuArr = res.content
            commit('SET_AUTH_ROUTERS', menuArr)
            resolve(res)
          } else {
            Vue.prototype.$message({
              type: 'warning',
              message: res.message
            })
          }
        }).catch((error) => {
          reject(error)
        })
      })
    },
    // 获取路由菜单
    saveDictObj ({ commit }) {
      return new Promise((resolve, reject) => {
        // 获取权限菜单
        Vue.prototype.$$get(api.dict.dictAll()).then(res => {
          if (res.success) {
            // 将后台返回的对象转换为数组对象
            let arr = []
            for (let item in res.content) {
              arr.push({
                code: item, // code值
                list: res.content[item] // 对应的字典项
              })
            }
            commit('SET_DICT_OBJ', arr)
            resolve(res)
          } else {
            Vue.prototype.$message({
              type: 'warning',
              message: res.message
            })
          }
        }).catch((error) => {
          reject(error)
        })
      })
    },
    // 获取用户信息
    GetInfo ({ commit, state }) {
      return new Promise((resolve, reject) => {
        // getInfo(state.token).then(response => {
        //   const data = response.data
        //   if (data.roles && data.roles.length > 0) { // 验证返回的roles是否是一个非空数组
        //     commit('SET_ROLES', data.roles)
        //   } else {
        //     reject('getInfo: roles must be a non-null array !')
        //   }
        //   commit('SET_NAME', data.name)
        //   commit('SET_AVATAR', data.avatar)
        //   resolve(response)
        // }).catch(error => {
        //   reject(error)
        // })
      })
    },
    // 登出
    LogOut ({ commit }) {
      return new Promise((resolve, reject) => {
        Vue.prototype.$$get(api.logout()).then((response) => {
          if (response.success) {
            commit('SET_TOKEN', '')
            commit('SET_AUTH_ROUTERS', [])
            commit('SET_DICT_OBJ', [])
            commit('SET_ACCOUNT_INFO', null)
            commit('SET_OSS_OBJ', null)
            // commit('SET_ROLES', [])
            // 清除TOKEN
            removeToken()
            // 清除路由
            removeRouter()
            // 清楚用户信息
            removeUserInfo()
            localStorage.clear()
            resolve()
          } else {
            Vue.prototype.$message({
              type: 'warning',
              message: response.message
            })
          }
        }).catch((error) => {
          reject(error)
        })
      })
    },
    // 前端 登出
    FedLogOut ({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        commit('SET_AUTH_ROUTERS', [])
        commit('SET_DICT_OBJ', [])
        commit('SET_ACCOUNT_INFO', null)
        // 清除TOKEN
        removeToken()
        // 清除路由
        removeRouter()
        // 清楚用户信息
        removeUserInfo()
        localStorage.clear()
        resolve()
      })
    }
  }
}
export default user
